package com.guxuede.mina.codefactory;

import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

import com.guxuede.mina.bean.HttpMessage;


public class HttpEncoder extends ProtocolEncoderAdapter{

	private final Charset charset;
	
	public HttpEncoder(Charset charset) {
		this.charset=charset;
	}
	
	@Override
	public void encode(IoSession sessiom, Object message, ProtocolEncoderOutput out)throws Exception {
		HttpMessage response=(HttpMessage)message;
		
		CharsetEncoder ce = charset.newEncoder();
		IoBuffer buffer = IoBuffer.allocate(100).setAutoExpand(true);
		if(response.head!=null){
			buffer.putString(response.head, ce);
		}
		if(response.body!=null){
			buffer.put(response.body);
			response.body.rewind();
		}
		buffer.flip();
		out.write(buffer);
	}

}
